﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Core.Logger;

namespace Core
{
    /// <summary>
    /// Category object which contains the BE Category elements.
    /// </summary>
    public class Category
    {
        /// <summary>
        /// Category Items collection.
        /// </summary>
        public List<CategoryItem> CategoryItems { get; private set; }

        /// <summary>
        /// Parses the Category XML element and populates the <see cref="CategoryItems"/> collection.
        /// </summary>
        /// <param name="element">WordPress XML content.</param>
        public void Parse(XElement element)
        {
            LoggerInstance.Append("Start parsing categories");
            this.CategoryItems = new List<CategoryItem>();

            XNamespace ns = "http://wordpress.org/export/1.0/";
            IEnumerable<XElement> categories = element.Elements("channel").Elements(ns + "category");

            foreach (XElement category in categories)
            {
                CategoryItem categoryItem = new CategoryItem();
                categoryItem.Id = Guid.NewGuid();
                categoryItem.Name = (string) category.Element(ns + "cat_name");
                categoryItem.Description = (string) category.Element(ns + "cat_name");
                categoryItem.WpNiceName = (string) category.Element(ns + "category_nicename");
                categoryItem.WpParentId = (string) category.Element(ns + "category_parent") ?? String.Empty;

                this.CategoryItems.Add(categoryItem);
            }

            this.SetParentCategory();
            LoggerInstance.Append("End parsing categories");
        }

        /// <summary>
        /// Sets the value of the parent attribute. The WpParentId value is set when parsing category 
        /// which holds the name of the parent category. Need to translate this name to the parent Id.
        /// </summary>
        private void SetParentCategory()
        {
            foreach (CategoryItem categoryItem in this.CategoryItems)
            {
                if (!String.IsNullOrEmpty(categoryItem.WpParentId))
                {
                    categoryItem.ParentId =
                        this.CategoryItems.Find(item => item.Name == categoryItem.WpParentId).Id.ToString();
                    if (categoryItem.ParentId == Guid.Empty.ToString())
                    {
                        categoryItem.ParentId = String.Empty;
                    }
                }
            }
        }

    }
}